package com.app.yourradioapp593.activities;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import com.app.yourradioapp593.Config;
import com.app.yourradioapp593.R;
import com.app.yourradioapp593.database.prefs.SharedPref;
import com.app.yourradioapp593.utils.Constant;
import com.app.yourradioapp593.utils.Tools;

public class ActivityWebView extends AppCompatActivity {

    WebView webView;
    ProgressBar progressBar;
    Button btnFailedRetry;
    View lytFailed;
    String strUrl;
    String strTitle;
    SharedPref sharedPref;
    private Toolbar toolbar;
    private ImageButton btnBack;
    private TextView toolbarTitle;
    OnBackPressedDispatcher onBackPressedDispatcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.getTheme(this);
        setContentView(R.layout.activity_webview);
        Tools.setNavigation(this);
        sharedPref = new SharedPref(this);
        webView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);
        btnFailedRetry = findViewById(R.id.btn_failed_retry);
        lytFailed = findViewById(R.id.lyt_failed);
        toolbarTitle = findViewById(R.id.toolbar_title);
        toolbar = findViewById(R.id.toolbar);
        btnBack = findViewById(R.id.btn_back);

        Intent intent = getIntent();
        if (null != intent) {
            strTitle = intent.getStringExtra("title");
            strUrl = intent.getStringExtra("url");
        }

        loadData();

        btnFailedRetry.setOnClickListener(view -> {
            lytFailed.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
            loadData();
        });

        setupToolbar();
        setStatusBar();
//        setBackgroundColor();
        handleOnBackPressed();

    }

    public void handleOnBackPressed() {
        onBackPressedDispatcher = getOnBackPressedDispatcher();
        onBackPressedDispatcher.addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                finish();
            }
        });
    }

    private void setupToolbar() {
        toolbarTitle.setText(strTitle);
        btnBack.setOnClickListener(v -> new Handler(Looper.getMainLooper()).postDelayed(this::finish, Constant.DELAY_CLICK));
        themeColor();
    }

    private void themeColor() {
        if (sharedPref.getIsDarkTheme()) {
            toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_toolbar));
            toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.color_white));
        } else {
            if (Config.ENABLE_NEW_UI) {
                toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_background));
                toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.grey));
                btnBack.setColorFilter(ContextCompat.getColor(this, R.color.grey), PorterDuff.Mode.SRC_ATOP);
            } else {
                toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_primary));
                toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.color_white));
                btnBack.setColorFilter(ContextCompat.getColor(this, R.color.color_white), PorterDuff.Mode.SRC_ATOP);
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void loadData() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportZoom(true);

        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.setWebViewClient(new MyWebViewClient());

        if (strUrl.startsWith("http://") || strUrl.startsWith("https://") || strUrl.startsWith("www")) {
            webView.loadUrl(strUrl);
        } else {
            webView.setBackgroundColor(Color.TRANSPARENT);
            String bg_paragraph;
            if (sharedPref.getIsDarkTheme()) {
                bg_paragraph = "<style type=\"text/css\">body{color: #eeeeee;} a{color:#ffffff; font-weight:bold;}";
            } else {
                bg_paragraph = "<style type=\"text/css\">body{color: #000000;} a{color:#1e88e5; font-weight:bold;}";
            }

            String font_style_default = "<style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/font/custom_font.ttf\")}body {font-family: MyFont; font-size: medium; overflow-wrap: break-word; word-wrap: break-word; -ms-word-break: break-all; word-break: break-all; word-break: break-word; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto;}</style>";

            String textHtml = "<html><head>"
                    + font_style_default
                    + "<style>img{max-width:100%;height:auto;} figure{max-width:100%;height:auto;} iframe{width:100%;}</style> "
                    + bg_paragraph
                    + "</style></head>"
                    + "<body>"
                    + strUrl
                    + "</body></html>";

            String mimeType = "text/html; charset=UTF-8";
            String encoding = "utf-8";
            webView.loadDataWithBaseURL(null, textHtml, mimeType, encoding, null);
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            //start intent for "tel:" links
            if (url != null && url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();
                return true;
            }

            //start intent for "sms:" links
            if (url != null && url.startsWith("sms:")) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                startActivity(intent);
                view.reload();
                return true;
            }

            //start intent for "sms:" links
            if (url != null && url.startsWith("mailto:")) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                startActivity(intent);
                view.reload();
                return true;
            }

            if (url != null && url.startsWith("http://pin.bbm.com/")) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setPackage("com.bbm");
                try {
                    startActivity(i);
                } catch (ActivityNotFoundException e) {
                    i.setPackage(null);
                    startActivity(i);
                }
                view.reload();
                return true;
            }


            if (url != null && url.startsWith("https://api.whatsapp.com/")) {

                PackageManager packageManager = getPackageManager();
                Intent i = new Intent(Intent.ACTION_VIEW);
                try {
                    i.setPackage("com.whatsapp");
                    i.setData(Uri.parse(url));
                    if (i.resolveActivity(packageManager) != null) {
                        startActivity(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                view.reload();

                return true;
            }

            if (url != null && url.startsWith("https://www.instagram.com/")) {

                PackageManager packageManager = getPackageManager();
                Intent i = new Intent(Intent.ACTION_VIEW);
                try {
                    i.setPackage("com.instagram.android");
                    i.setData(Uri.parse(url));
                    if (i.resolveActivity(packageManager) != null) {
                        startActivity(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                view.reload();

                return true;
            }

            if (url != null && url.startsWith("instagram://")) {

                PackageManager packageManager = getPackageManager();
                Intent i = new Intent(Intent.ACTION_VIEW);
                try {
                    i.setPackage("com.instagram.android");
                    i.setData(Uri.parse(url));
                    if (i.resolveActivity(packageManager) != null) {
                        startActivity(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                view.reload();

                return true;
            }

            if (url != null && url.startsWith("https://maps.google.com/")) {

                PackageManager packageManager = getPackageManager();
                Intent i = new Intent(Intent.ACTION_VIEW);
                try {
                    i.setPackage("com.google.android.apps.maps");
                    i.setData(Uri.parse(url));
                    if (i.resolveActivity(packageManager) != null) {
                        startActivity(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                view.reload();

                return true;
            }

            if (url != null && url.startsWith("file:///android_asset/[external]http")) {
                url = url.replace("file:///android_asset/[external]", "");
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } else {
                view.loadUrl(url);
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
        }

        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), getResources().getString(R.string.failed_text), Toast.LENGTH_LONG).show();
            view.loadUrl("about:blank");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_webview, menu);
        return true;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int itemId = menuItem.getItemId();
        if (itemId == android.R.id.home) {
            onBackPressedDispatcher.onBackPressed();
            return true;
        } else if (itemId == R.id.open_in_browser) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl.trim())));
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    private void setStatusBar() {
        if (sharedPref.getIsDarkTheme()) {
            Tools.setStatusBarColor(this, findViewById(R.id.root_view), ContextCompat.getColor(this, R.color.color_dark_status_bar));
        } else {
            if (Config.ENABLE_NEW_UI) {
                Tools.setStatusBarColor(this, findViewById(R.id.root_view), ContextCompat.getColor(this, R.color.color_white));
            } else {
                Tools.setStatusBarColor(this, findViewById(R.id.root_view), ContextCompat.getColor(this, R.color.color_light_status_bar));
            }
        }
    }

//    private void setBackgroundColor() {
//        if (sharedPref.getIsDarkTheme()) {
//            findViewById(R.id.background_view).setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_background));
//        } else {
//            findViewById(R.id.background_view).setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_background));
//        }
//    }

}
